package cn.codergege.shiro.service.impl;

import java.util.List;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.crypto.hash.SimpleHashRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.codergege.shiro.dao.UserMapper;
import cn.codergege.shiro.model.User;
import cn.codergege.shiro.service.Md5Update;

@Service("md5Update")
public class Md5UpdateImpl implements Md5Update {

	private final Logger log = LoggerFactory.getLogger(Md5UpdateImpl.class);
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public void update() throws Exception {
		// 1. get all users that password_salt is null;
		List<User> users = userMapper.getNullSaltUsers();
		// 2. 更新 salt, password.
		for(User user: users) {
			user.setPasswordSalt(user.getUsername());
			
			String algorithmName = "MD5";
			Object source = user.getPassword();
			Object salt = user.getPasswordSalt();
			int hashIterations = 2;
			SimpleHash password = new SimpleHash(algorithmName, source, salt, hashIterations);
			user.setPassword(password.toString());
			log.info("加密后的密码为: " + password.toString());

			// 3. update
			userMapper.updateByPrimaryKeySelective(user);
		}
		
	}

}
